//index.js
import { Init } from '../../init.js';
import { config } from '../../utils/config.js';
import { CouponModel } from '../../model/coupon.js';
import { showLoading,  hideLoading } from '../../components/mask.js';


//获取应用实例
const app = getApp(); 
const init = new Init();
const couponModel = new CouponModel();

Page({
  data: {
	isMember: false, // 是否是Bk会员
	shadow: false,
	isPlus: 'N', // 默认该会员不是京东plus
	message: "hello, world",
	memberCodeDesc: '会员卡码',
	memberCardDesc: '我的卡券',
	memberKingDesc: 'KING币数',
	avatorDefaultUrl: 'https://scrm.bkchina.cn/scrm-bk-jd/business/shops/upload/head/huangguan.png',
	avatorUrl: '',
	cardNo: '', // 会员卡号
	cardNoImg: '', // 会员条码
	plusProductName: '霸王鸡盒',
	plusProductNow: '4',
	plusProductUnit: '元',
	plusProductPast: '14元起',
	oridinaryProductNow: '4',
	oridinaryProductUnit: '¥',
	oridinaryProductPast: '14元起',
	couponImageList: [], // 传入banners数组
	productName: "",
	memberInfo: {}, // 会员信息
	isShowMemberCard: false, // 点击放大会员卡号
	plusProductList: [], // 京东plus专区
	oridinaryProductList: [] ,// 普通用户专区
	oridinaryOldPriceDesc: '' ,// 普通用户专区原价描述
	couponNum: '', // 卡券数量
	memberScroe: '', // 积分
	couponInstanceCode: '' ,// 领取成功，查询优惠券详情
	tipMsg: '' // 优惠券领取上限
  },
  
  onLoad: function() {
	  console.log("----Page onload----");
	  console.log(app.globalData.isSubmitMemberInfo);
	  if(!app.globalData.isSubmitMemberInfo) {
		  const _that = this;
		  console.log("----onload----");
		  showLoading();
		  const userOauthInfo = app.getUserOpenId();
		  const userAccessTokeInfo = app.getUserAccessToken();
		  Promise.all([userOauthInfo, userAccessTokeInfo]).then(res => {
			  console.log("--获取两个函数返回信息--");
			  console.log(res[0]);
			  console.log("================");
			  console.log(res[1]);
			  if(res[0] && res[1].access_token) {
				  console.log("全局用户openId");
				  console.log(app.globalData.openId);
				  console.log("全局用户信息");
				  console.log(app.globalData.userInfo);
				  const submitInfo = init.submitUserInfo(res[0]);
				  submitInfo.then((res) => {
					  console.log("===提交用户信息结果====");
					  console.log(res);
					  app.globalData.isSubmitMemberInfo = true
					  hideLoading();
					  _that._initData();
				  });
			  }
		  });
	  }
  },
  
  onShow: function() {
	  // 初始化首页信息
	  console.log("show初始化信息");
	  console.log(app.globalData.isSubmitMemberInfo);
	  let userOpenId = jd.getStorageSync('openId') || app.globalData.openId;
	  if (app.globalData.isSubmitMemberInfo) {
		  showLoading();
		  const memberInfo = couponModel.getMemberInfo(userOpenId);
		  memberInfo.then(res => {
			  if(res.cardNo) {
				  this.setData({
					  isMember: true
				  });
			  }
			  this.setData({
				   memberInfo: res,
				   avatorUrl: res.memberPhoto || app.globalData.userInfo.avatar_url || this.data.avatorDefaultUrl,
				   couponNum: res.couponNum || '--',
				   memberScroe: res.memberScroe || '--',
				   cardNo: res.cardNo,
				   cardNoImg: res.cardNoPath
			  });
			  hideLoading();
		  });
	  }
  },
  
  // 获取用户手机号
  handleGetUserPhone: function(e) {
	  // 查询用户手机号授权过
	  console.log("===获取用户手机号====");
	  console.log(e);
	  if(e.detail.isOuthUserPhone) {
		  jd.showModal({
			  title: '手机号授权信息',
			  content: '手机号已授权,点击确定即可正常使用',
			  showCancel: false
		  });
	  }
	  // showLoading();
	  console.log("==openId===");
	  console.log(config.user_open_id);
	  console.log("==accessToken===");
	  console.log(config.user_access_token);
	  console.log("===global===openId===");
	  console.log(app.globalData.openId);
	  console.log("===global===token===");
	  console.log(app.globalData.accessToken);
	  let userOpenId = jd.getStorageSync('openId') || app.globalData.openId;
	  const memberPhoneInfo = 
				couponModel.getPhoneNumber(userOpenId, app.globalData.accessToken);
	  memberPhoneInfo.then((res) => {
		  console.log("===获取用户手机号===");
		  console.log(res);
		  // 用户手机号授权拒接
		  if(res && res.code !== 0) {
			  const memberInfo = couponModel.getMemberInfo(userOpenId);
			  memberInfo.then((res) => {
				  console.log("===获取会员信息===");
				  console.log(res);
				  this.setData({
					 isMember: true
				  });
				  // hideLoading();
				  this.onShow();
			  });
		  }
	  });
  },
  
  // 点击封面跳转
  handleBannerUrl: function(e) {
	  if(e.detail && e.detail.imgUrl) {
		  jd.navigateTo({
		  	url: '/pages/web-view/index?imgUrl=' + e.detail.imgUrl
		  });
	  }
  },
  
  // 跳转到我的卡包
  jumpMyCoupon: function() {
	  // 如果不是会员，那么弹出手机号授权框
	  jd.navigateTo({
		  url: '/pages/coupon-box/index'
	  });
  },
  
  // 领取优惠券
  receiveCoupon: function (e) {
	  const that = this;
	  this._initShadeInfo();
	  let coupouId = e.currentTarget.dataset.couponid;
	  let coupouName = e.currentTarget.dataset.couponname;
	  let type = e.currentTarget.dataset.type;
	  if(type && type == 'plus') {
		  // 如果是汉堡王会员
		  if(this.data.isMember) {
			  jd.getPlusInfo({
				  success: function(res) {
					  console.log("===京东plus会员授权成功====");
					  console.log(JSON.stringify(res));
					  const isPlusInfo = init.submitIsPlusInfo(res);
					  isPlusInfo.then(res => {
						  console.log("提交plus会员信息给后台");
						  console.log(res);
						  // 是京东plus
						  if(res && res.isPlus && res.isPlus == 'Y') {
							  that.data.isPlus = res.isPlus;
							  // 领取流程
							  if (coupouId) {
									  const couponReceive = couponModel.getCoupon(coupouId, res.openId, that.data.isPlus);
									  couponReceive.then((res) => {
										  console.log("----领取优惠券信息----");
										  console.log(res);
										  if(res.code == '200') {
											  let tempCouponInstanceCode = '';
											  if(res && res.data && res.data.couponInstanceCode) {
												  tempCouponInstanceCode = res.data.couponInstanceCode
											  }
											  that.setData({
												  shadow: true,
												  productName: coupouName,
												  couponInstanceCode: tempCouponInstanceCode
											  }); 
											  that.onShow();
										  } else {
											 that.setData({
												 tipMsg: res.message,
												 shadow: true
											 });
										  }
									  });
							  }
						  } else {
							  that.data.isPlus = 'N';
							  // 提示弹出框
							  console.log("到这步===");
							  console.log(res.openId);
							  const memberInfo = couponModel.getMemberInfo(res.openId);
								  memberInfo.then(res => {
									  console.log(res);
									 if(res && res.isPlus && res.isPlus == 'N') {
										 jd.showModal({
											  title: '京东Plus会员信息',
											  content: res.verbalTrick,
											  showCancel: false
										 });
									 }	  
								  });
						  }
					  });
				  },
				  fail: function(err) {
					  console.log("===京东plus会员授权失败====");
					  console.log(JSON.stringify(err));
				  }
			  });
		  }
	  } else {
		  this._initShadeInfo();
		  let userOpenId = jd.getStorageSync('openId') || app.globalData.openId;
		  let coupouId = e.currentTarget.dataset.couponid;
		  let coupouName = e.currentTarget.dataset.couponname;
		  if (coupouId) {
		  		  const couponReceive = couponModel.getCoupon(coupouId, userOpenId, 'N');
		  		  couponReceive.then((res) => {
		  			  console.log("----领取优惠券信息----");
		  			  console.log(res);
		  			  if(res.code == '200') {
		  				  let tempCouponInstanceCode = '';
		  				  if(res && res.data && res.data.couponInstanceCode) {
		  				  	  tempCouponInstanceCode = res.data.couponInstanceCode
		  				  }
		  				  this.setData({
		  					  shadow: true,
		  					  productName: coupouName,
		  					  couponInstanceCode: tempCouponInstanceCode
		  				  }); 
		  				  this.onShow();
		  			  } else {
		  				 this.setData({
		  					 tipMsg: res.message,
		  					 shadow: true
		  				 });
		  			  }
		  		  });
		  }
	  }
  },
  
  // 处理会员卡码信息
  handleMemberCardImg: function () {
	  this._handleRefreshCardNo();
	  // this.setData({
		 //  isShowMemberCard: true
	  // });
  },
  
  // 关闭会员卡码
  handleCloseImage: function() {
	  this.setData({
	  	  isShowMemberCard: false
	  });
  },
  
  // 关闭浮层
  handleCloseShade: function(e) {
	  if(e.detail && !e.detail.shadow) {
		  this.setData({
		  	  shadow: e.detail.shadow
		  });
	  }
  },
  
  // 初始化首页信息
  _initData: function() {
	  let userOpenId = jd.getStorageSync('openId') || app.globalData.openId;
	  const bannerList = couponModel.getBanner(); // 加载头部banner信息
	  const memberInfo = couponModel.getMemberInfo(userOpenId); // 加载会员信息
	  const couponList = couponModel.getCouponCategory(); // 加载优惠券架
	  
	  let tempPlusProductList = [];
	  let tempOrdinaryProductList = [];
	  Promise.all([bannerList, memberInfo, couponList]).then(res => {
		  console.log('====用户信息====');
		  console.log(res[1]);
		  // 说明是会员
		  if(res[1].cardNo) {
			  this.setData({
				  isMember: true
			  });
		  }
		  for(let item of res[2].data.couponExps) {
			  // 京东plus专享
			  if (item.couponCategoryId == 17) {
				  tempPlusProductList.push(item);
			  } else {
				  tempOrdinaryProductList.push(item);
			  }
		  }
		  this.setData({
			  couponImageList: res[0].data.homeMiddles,
			  memberInfo: res[1],
			  avatorUrl: res[1].memberPhoto || app.globalData.userInfo.avatar_url || this.data.avatorDefaultUrl,
			  couponNum: res[1].couponNum || '--',
			  memberScroe: res[1].memberScroe || '--',
			  cardNo: res[1].cardNo,
			  cardNoImg: res[1].cardNoPath,
			  plusProductList: tempPlusProductList,
			  oridinaryProductList: tempOrdinaryProductList
		  });
	  });
  },
  
  // 初始化弹窗信息
  _initShadeInfo: function() {
	  this.setData({
		  productName: '',
		  couponInstanceCode: '',
		  tipMsg: ''
	  });
  },
  
  // 查询优惠券架
  _loadGetCouponCategory: function() {
	  let tempPlusProductList = [];
	  let tempOrdinaryProductList = [];
	  const couponList = couponModel.getCouponCategory();
	  couponList.then((res) => {
		  for(let item of res.data.couponExps) {
			  // 京东plus专享
			  if (item.couponCategoryId == 17) {
				  tempPlusProductList.push(item);
			  } else {
				  tempOrdinaryProductList.push(item);
			  }
		  }
		  
		  this.setData({
			  plusProductList: tempPlusProductList,
			  oridinaryProductList: tempOrdinaryProductList
		  });
		})
	},
	  
  
  // 刷新会员卡码
  _handleRefreshCardNo: function() {
  	  const refreshCardNo = couponModel.getRefreshCardNo(this.data.cardNo);
	  refreshCardNo.then((res) => {
		  this.setData({
			  isShowMemberCard: true,
			  cardNo: res.data.cardNo,
			  cardNoImg: res.data.cardNoPath
		  });
	  });
  },
  
  // 加载会员信息
  _loadMemberInfo: function() {
	  let userOpenId = jd.getStorageSync('openId') || app.globalData.openId;
	  const memberInfo = couponModel.getMemberInfo(userOpenId);
	  memberInfo.then((res) => {
		  this.setData({
			  memberInfo: res,
			  avatorUrl: res.memberPhoto || this.data.avatorDefaultUrl,
			  cardNo: res.cardNo,
			  cardNoImg: res.cardNoPath
		  });
	  });
  },
  
  // 处理原价信息
 _handleOldPrice: function(oldPrice) {
	 let oldPriceDesc = "";
	 if (oldPrice) {
		 oldPriceDesc = oldPrice + "元起"
	 }
	 return oldPriceDesc;
 },
  
  // 加载banner信息
  _loadBannerList: function() {
	 const bannerList = couponModel.getBanner();
	 bannerList.then((res) => {
		 this.setData({
			 couponImageList: res.data.homeMiddles
		 });
	 });
  }
  
});